package com.app.serve.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 描述: 打印请求和响应
 */
@Aspect
@Controller
public class WebLogAspect {

    private static final Logger log = LoggerFactory.getLogger(WebLogAspect.class);

    /**
     * 拦截包下controllers所有请求
     */
    @Pointcut("execution(public * com.app.serve.api.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {

        // 收到请求, 记录请求内容

        // 获取http对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        // 获取url
        log.info("URL : " + request.getRequestURL().toString());
        // 获取提交方式
        log.info("HTTP_METHOD :" + request.getMethod());
        // 获取ip信息
        log.info("IP : " + request.getRemoteAddr());
        // 获取类的信息/签名信息
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        // 参数信息
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 返回时拦截
     * @param res 返回内容
     * @throws JsonProcessingException
     */
    @AfterReturning(returning = "res", pointcut = "webLog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        // 处理完请求，返回内容
        // ObjectMapper: fastJson 提供的对象转json格式的工具
        log.info("RESPONSE : " + new ObjectMapper().writeValueAsString(res));
    }
}
